import '../../pojo/Enums.dart';
import '../../pojo/ImPojo.dart';
import 'BaseBloc.dart';

final class GroupUserListCubit extends BaseBloc<GroupUserListEvent, GroupUserListState> {
  GroupUserListCubit(ImSession imSession) : super(GroupUserListState.loading(imSession, imSession.group!)) {
    on<GroupUserListKeyEvent>((event, emit){
      _searchKey(this.state, event.search);
    });
    on<GroupUserListSearchEvent>((event, emit){
      _search(this.state, event.search);
    });
  }

  _searchKey(GroupUserListState oldState, String search) {
    emit(oldState.copy(search: search));
  }

  _search(GroupUserListState oldState, String search) {
    var searchResults = oldState.imGroup.groupUserList!.where((gu)=>(gu.userName??(gu.user?.userName??'')).contains
      (search)).toList(growable: false);
    emit(oldState.copy(searchResults: searchResults, search: search));
  }
}

final class GroupUserListState {
  final ImSession imSession;
  final ImGroup imGroup;
  final LoadingState state;
  final String search;
  final List<ImGroupUser> searchResults;

  GroupUserListState._({
    this.state = LoadingState.loading,
    required this.imSession,
    required this.imGroup,
    this.searchResults = const <ImGroupUser>[],
    this.search = '',
  });

  GroupUserListState copy({List<ImGroupUser>? searchResults, ImGroup? imGroup, String? search,
    LoadingState? state}) {
    return GroupUserListState._(
      imSession: this.imSession,
      imGroup: imGroup?? this.imGroup,
      searchResults: searchResults ?? this.searchResults,
      search: search?? this.search,
      state: this.state,
    );
  }

  GroupUserListState.loading(ImSession imSession, ImGroup imGroup) : this._(imSession: imSession, imGroup: imGroup,
      searchResults: imGroup.groupUserList!.toList());

  // GroupUserListState.success(ImGroup imGroup, List<ImGroupUser> searchResults, String search)
  //     : this._(state: LoadingState.success, imGroup: imGroup, searchResults: searchResults, search: search);

  @override
  List<Object?> get props => [imSession, imGroup, state, search, searchResults];
}

class GroupUserListEvent {}
class GroupUserListKeyEvent extends GroupUserListEvent {
  String search;
  GroupUserListKeyEvent(this.search);
}
class GroupUserListSearchEvent extends GroupUserListEvent {
  String search;
  GroupUserListSearchEvent(this.search);
}

